package com.littlebee.storychild.ui;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.littlebee.storychild.R;
import com.littlebee.storychild.common.utils.LogUtil;
import com.littlebee.storychild.common.utils.ToastUtil;
import com.littlebee.storychild.common.utils.sharePrefUtils.SharePrefUtil;
import com.zss.library.activity.BaseActivity;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.SharedPrefUtils;

import java.util.Locale;

import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;

/**
 * Created by liaoyong on 17/11/2017.
 */

public class VoiceCallingActivity extends BaseActivity
    implements View.OnClickListener {
    private ImageView btn_speaker;
    private TextView tv_tips;
    private RtcEngine mRtcEngine;// Tutorial Step 1

    @Override
    public int getLayoutResId() {
        return R.layout.activity_voicecalling;
    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        toolbar.setTitle(getString(R.string.online_calling_txt));
    }

    @Override
    public void initView() {
        super.initView();

        btn_speaker = (ImageView) findViewById(R.id.iv_speaker);
        btn_speaker.setOnClickListener(this);
        tv_tips = (TextView) findViewById(R.id.tv_tip);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        initAgoraEngineAndJoinChannel();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_speaker) {
            if (btn_speaker.isSelected()) {
                stopVoice();
            } else {
                startVoice();
            }
        }
    }


    private void initAgoraEngineAndJoinChannel() {
        initializeAgoraEngine();     // Tutorial Step 1
        joinChannel();               // Tutorial Step 2
        startVoice();
    }

    // Tutorial Step 2
    private void joinChannel() {
        String channelName = SharePrefUtil.getInstance(this).getStringValue("DID");
        mRtcEngine.joinChannel(null, channelName, "Extra Optional Data", 0); // if you do not specify the uid, we will generate the uid for you
        tv_tips.append("实时通话正尝试加入通道：" + channelName + "...\n");
    }

    private void startVoice() {
        btn_speaker.setSelected(true);
        btn_speaker.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
        mRtcEngine.setEnableSpeakerphone(true);
        tv_tips.append("正在实时通话中...\n");
    }

    private void stopVoice() {
        btn_speaker.setSelected(false);
        btn_speaker.clearColorFilter();
        mRtcEngine.setEnableSpeakerphone(false);
        tv_tips.append("停止实时通话...\n");
    }

    // Tutorial Step 3
    public void onEncCallClicked(View view) {
        finish();
    }

    // Tutorial Step 1
    private void initializeAgoraEngine() {
        try {
            mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
        } catch (Exception e) {
            LogUtil.d("liaoyong:init speak error..." );
            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
        }
    }

    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() { // Tutorial Step 1

        @Override
        public void onUserOffline(final int uid, final int reason) { // Tutorial Step 4
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onRemoteUserLeft(uid, reason);
                }
            });
        }

        @Override
        public void onUserMuteAudio(final int uid, final boolean muted) { // Tutorial Step 6
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onRemoteUserVoiceMuted(uid, muted);
                }
            });
        }
    };

    // Tutorial Step 4
    private void onRemoteUserLeft(int uid, int reason) {
        ToastUtil.displayShortToast("onRemoteUserLeft");
//        showLongToast(String.format(Locale.US, "user %d left %d", (uid & 0xFFFFFFFFL), reason));
//        View tipMsg = findViewById(R.id.quick_tips_when_use_agora_sdk); // optional UI
//        tipMsg.setVisibility(View.VISIBLE);
    }

    // Tutorial Step 6
    private void onRemoteUserVoiceMuted(int uid, boolean muted) {
        ToastUtil.displayShortToast(String.format(Locale.US, "user %d muted or unmuted %b", (uid & 0xFFFFFFFFL), muted));
    }
}
